<template>
  <div>
    <div class="top-panel__box">
      <el-form size="small" >
        <el-row>
          <el-col :span="6">
            <el-form-item label="差错类型" label-width="100px">
              <el-select v-model="formData.exceptionType" clearable>
                <el-option v-for="(key, value, index) in dicts['error_type'].childMap"  :key="index" :label="key" :value="value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品类型" label-width="100px">
              <el-select v-model="formData.productType" clearable>
                <el-option v-for="(key, value, index) in dicts['error_product_type'].childMap"  :key="index" :label="key" :value="value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="当前处理状态" label-width="100px">
              <el-select v-model="formData.exceptionStatus" clearable>
                <el-option v-for="(key, value, index) in EXCEPTION_STATUS_CODE"  :key="index" :label="key" :value="value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top: 10px">
          <el-col :span="5">
            <el-form-item>
              <el-input clearable v-model="formData.bizSerialNo" placeholder="输入进件/借款编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin-left: 10px">
            <el-form-item>
              <el-input clearable v-model="formData.customerCondition" placeholder="输入申请人姓名/身份证/手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin-left: 10px">
            <el-form-item>
              <el-input clearable v-model="formData.acceptorCondition" placeholder="输入业务受理人姓名/工号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin-left: 10px">
            <el-form-item>
              <organization-cascader v-model="formData.acceptorOrgNo" :placeholder="'选择受理机构'"></organization-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top: 10px" justify="center">
          <el-col :span="16">
            <el-date-picker
              type="date"
              size="small"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd"
              style="width:255px"
              placeholder="差错进入时间起"
              v-model="formData.enterBeginTime"
            />
            <span>—</span>
            <el-date-picker
              type="date"
              size="small"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width:255px"
              placeholder="差错进入时间止"
              v-model="formData.enterEndTime"
            />
          </el-col>
          <el-col :span="8">
            <div style="float: right; margin-right: 20px">
              <el-button size="small" icon="el-icon-search" type="primary" @click="onSearch()">查询</el-button>
              <el-button size="small" icon="el-icon-refresh-right" @click="onReset()">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div style="float: right; margin-bottom: 10px">
      <el-button size="small" plain type="primary" @click="onBatchLanuch">批量重新发起</el-button>
      <el-button size="small" plain type="danger" @click="onBatchBack">批量回退原节点</el-button>
      <el-button size="small" plain type="info" @click="onBatchCancelFinish">批量异常结案</el-button>
      <el-button size="small" plain type="info" @click="onBatchCancelUpload">批量取消上传</el-button>
    </div>
    <el-table border :data="listData" @selection-change="onTableSelectionChange">
      <el-table-column :selectable="isCanSelect"  type="selection" width="55"></el-table-column>
      <el-table-column v-for="( column, index ) in TABLE_HEAD" :key="index" :prop="column.prop" :label="column.label" :show-overflow-tooltip="true" :width="getColumn(column)" ></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="350">
        <template slot-scope="scope">
          <el-button v-if="scope.row.exceptionStatus == 'NEW'" type="primary" size="small" @click="onLanuch(scope.row)">重新发起</el-button>
          <el-button v-if="scope.row.exceptionType == 'BIZ_ERR' && scope.row.exceptionStatus == 'NEW'" type="danger" size="small" @click="onBack(scope.row)">回退原节点</el-button>
          <el-button v-if="scope.row.exceptionType == 'BIZ_ERR' && scope.row.exceptionStatus == 'NEW'" type="info" size="small" @click="onCancelFinish(scope.row)">异常结案</el-button>
          <el-button v-if="scope.row.exceptionType == 'UPLOAD_ERR' && scope.row.exceptionStatus == 'NEW'" type="info" size="small" @click="onCancelUpload(scope.row)">取消上传</el-button>
        </template>
    </el-table-column>
    </el-table>
    <div style="float:right; margin-top: 10px; margin-bottom: 10px">
      <el-pagination 
        @current-change="onPageChange"
        background layout="prev, pager, next, total" :total="total" ></el-pagination>
    </div>
  </div>
</template>

<script>
import { common } from '@/utils/common'
import { mapState } from 'vuex'
import { CONSTANT_OBJ } from '@/utils/constant'
import { getResidenceTime } from '@/utils/util'
import api from "./api/index.js";
import OrganizationCascader from '@/components/organizationCascader'

export const TABLE_HEAD = [
  { label: '序号', prop: 'index'},
  { label: '差错类型', prop: 'exceptionTypeStr'},
  { label: '产品类型', prop: 'productTypeStr'},
  { label: '进件/借款编号', prop: 'bizSerialNo'},
  { label: '申请人', prop: 'customerName'},
  { label: '申请人身份证号码', prop: 'idNbr'},
  { label: '申请人手机号码', prop: 'customerPhone'},
  { label: '业务受理人', prop: 'acceptorName'},
  { label: '业务受理机构', prop: 'acceptorOrgName'},
  { label: '进入差错前环节', prop: 'originCaseStatusStr'},
  { label: '差错原因', prop: 'exceptionReason'},
  { label: '进入时间', prop: 'enterTime'},
  { label: '差错停留时长', prop: 'stopTime'},
  { label: '当前处理状态', prop: 'exceptionStatusStr'},
  { label: '处理时间', prop: 'exitTime'}
]

export const EXCEPTION_STATUS_CODE = {
  'NEW': '未处理',
  'COMPLETED': '已处理',
}

export default {
  data () {
    return {
      EXCEPTION_STATUS_CODE,
      TABLE_HEAD,
      formData: {
        exceptionType: '',
        acceptorCondition: '',
        acceptorOrgNo: '',
        bizSerialNo: '',
        customerCondition: '',
        enterBeginTime: '',
        enterEndTime: '',
        productType: '',
        exceptionStatus: 'NEW',
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      listData: [],
      selectList: []
    }
  },
  components: {
    OrganizationCascader
  },
  computed: {
    ...mapState({
      dicts: state => state.common.dicts
    }),
    getColumn(){
      return function(column) {
        let width = '150'
        if (column.prop == 'index') {
          width = '50'
        } else if (column.prop == 'customerName') {
          width = '120'
        } else if (column.prop == 'exceptionReason') {
          width = '250'
        } else if (column.prop == 'enterTime' || column.prop == 'exitTime') {
          width = '180'
        } else if (column.prop == 'idNbr') {
          width = '200'
        }
        return width
      } 
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 查询
    onSearch () {
      this.formData.pageNum = 1
      this.getList()
      console.log(this.formData.exceptionType);
    },
    // 重置
    onReset () {
      this.formData.pageNum = 1
      Object.keys(this.formData).forEach(key => {
        if (key != 'pageNum' && key != 'pageSize' && key != 'exceptionStatus') {
          this.formData[key] = ''
        } else if  (key == 'exceptionStatus') {
          this.formData[key] = 'NEW'
        }
      });
      this.getList()
    },
    getList(){
      let parmas = { ...this.formData }
      parmas.enterEndTime = this.formData.enterEndTime !== '' && this.formData.enterEndTime !== null ? this.formData.enterEndTime + ' 23:59:59' : ''
      let validateDate = this.rulesDate(parmas.enterBeginTime, parmas.enterEndTime)
      if (!validateDate) {
        return false
      }
      // console.log('查询：', parmas);
      // console.log('查询》》》：', this.dicts['error_product_type'].childMap);
      api.queryByCondition(parmas).then(res => {
        const { responseCode, data: {list, total} } = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          this.listData = list || []
          this.total = Number(total || '0')
          this.listData.forEach((element, index) => {
            this.$set(element, 'index', index+1)
            // 处理任务停留时间
            if (element.exceptionStatus == 'NEW') {
              // 未处理
              element.exitTime = '-'
              this.$set(element, 'stopTime', getResidenceTime(element.enterTime)+'min')//任务停留时间
            } else {
              // 已处理
              this.$set(element, 'stopTime', '-')//任务停留时间
            }
            this.$set(element, 'productTypeStr', this.dicts['error_product_type'].childMap[element.productType] || element.productType)//任务停留时间
            // 差错类型
            this.$set(element, 'exceptionTypeStr', this.dicts['error_type'].childMap[element.exceptionType] || element.exceptionType)
            // 处理状态
            this.$set(element, 'exceptionStatusStr', this.EXCEPTION_STATUS_CODE[element.exceptionStatus] || element.exceptionStatus)
            // 前一个环节名称 - 转中文
            if (element.productType == 'JXD_DRAW') {
              this.$set(element, 'originCaseStatusStr', this.dicts["loan_status"].childMap[element.originCaseStatus] || element.originCaseStatus)
            } else {
              this.$set(element, 'originCaseStatusStr', this.dicts["case_status"].childMap[element.originCaseStatus] || element.originCaseStatus)
            }
          });
        }
      }).catch(()=>{})
    },
    /**
     * 校验结束时间不能小于开始时间
     */
     rulesDate (tempStart, tempEnd) {
      let start = new Date(tempStart).getTime() || ''
      let end = new Date(tempEnd).getTime() || ''
      if (start && end) {
        if (start > end) {
          this.$message.error('结束时间不能小于开始时间')
          return false
        } else {
          return true
        }
      }
      return true
    },
    // 是否可以选择
    isCanSelect (row) {
      return row.exceptionStatus == 'NEW'
    },
    onTableSelectionChange (e) {
      this.selectList = e
    },
    // 页码切换
    onPageChange (e){
      this.formData.pageNum = e
      console.log(this.formData.pageNum);
      this.getList()
    },
    // 批量操作的校验
    patchValidate() {
      if (this.selectList.length <= 0) {
        this.$message.warning('请选择案件')
        return false
      }
      // 选择相同类别
      let typeList = this.selectList.filter(v => {
        return v.exceptionType != this.selectList[0].exceptionType
      })
      if (typeList!= null && typeList.length > 0) {
        this.$message.warning('请选择相同异常类型案件')
        return false
      }
      return true
    },
    // 批量发起
    onBatchLanuch () {
      if (!this.patchValidate()){
        return false
      }
      // 筛选出批量回退。
      let dealList = this.selectList.filter(v => {
        return v.exceptionStatus == 'NEW'
      })
      common.confirmBatch('', '是否对差错操作重新发起？', '差错', this.selectList.length, dealList.length || 0).then(res => {
        if (res) {
          let ids = dealList.map(item => {
            return item.id
          })
          if (ids && ids.length > 0) {
            let data = {
              ids: ids,
              exceptionCategory: 'RESTART'
            }
            this.dealWithError(data)
          }
        }
      })
    },
    onLanuch (row) {
      common.confirmFn('', '是否对差错操作重新发起？').then(res => {
        if (res) {
          let data = {
            ids: [row.id],
            exceptionCategory: 'RESTART'
          }
          this.dealWithError(data)
        }
      })
    },
    // 批量回退
    onBatchBack () {
      if (!this.patchValidate()){
        return false
      }
      // 筛选出批量回退。
      let dealList = this.selectList.filter(v => {
        return v.exceptionType == 'BIZ_ERR' && v.exceptionStatus == 'NEW'
      })
      common.confirmBatch('进件/借款将会回到流入差错的前一个节点！', '是否将差错进件/借款回退原节点？', '差错进件/借款', this.selectList.length, dealList.length || 0).then(res => {
        if (res) {
          let ids = dealList.map(item => {
            return item.id
          })
          if (ids && ids.length > 0) {
            let data = {
              ids: ids,
              exceptionCategory: 'REFUND'
            }
            this.dealWithError(data)
          }
        }
      })
    },
    // 
    onBack () {
      common.confirmFn('进件/借款将会回到流入差错的前一个节点！', '是否将差错进件/借款回退原节点？').then(res => {
        if (res) {
          let data = {
            ids: [row.id],
            exceptionCategory: 'REFUND'
          }
          this.dealWithError(data)
        }
      })
    },
    // 批量异常结案
    onBatchCancelFinish () {
      if (!this.patchValidate()){
        return false
      }
      // 筛选出取消结案的。
      let dealList = this.selectList.filter(v => {
        return v.exceptionType == 'BIZ_ERR' && v.exceptionStatus == 'NEW'
      })
      common.confirmBatch('取消后，进件/借款将以取消/拒绝结案！', '是否取消差错进件/借款？', '差错进件/借款', this.selectList.length, dealList.length || 0).then(res => {
        if (res) {
          let ids = dealList.map(item => {
            return item.id
          })
          if (ids && ids.length > 0) {
            let data = {
              ids: ids,
              exceptionCategory: 'CANCEL_CASE'
            }
            this.dealWithError(data)
          }
        }
      })
    },
    // 异常结案
    onCancelFinish () {
      common.confirmFn('取消后，进件/借款将以取消/拒绝结案！', '是否取消差错进件/借款？').then(res => {
        if (res) {
          let data = {
            ids: [row.id],
            exceptionCategory: 'CANCEL_CASE'
          }
          this.dealWithError(data)
        }
      })
    },
    // 批量取消上传
    onBatchCancelUpload() {
      if (!this.patchValidate()){
        return false
      }
      // 筛选出可取消的。
      let dealList = this.selectList.filter(v => {
        return v.exceptionType == 'UPLOAD_ERR' && v.exceptionStatus == 'NEW'
      })
      common.confirmBatch('取消后，对应材料将不会上传至系统中！', '是否取消上传？', '差错', this.selectList.length, dealList.length || 0).then(res => {
          if (res) {
            let ids = dealList.map(item => {
              return item.id
            })
            if (ids && ids.length > 0) {
              let data = {
                ids: ids,
                exceptionCategory: 'CANCEL_UPLOAD'
              }
              this.dealWithError(data)
            }
          }
        })
    },
    // 取消上传
    onCancelUpload (row) {
      common.confirmFn('取消后，对应材料将不会上传至系统中！', '是否取消上传？').then(res => {
        if (res) {
          let data = {
            ids: [row.id],
            exceptionCategory: 'CANCEL_UPLOAD'
          }
          this.dealWithError(data)
        }
      })
    },
    // 调接口处理异常 "RESTART 重新发起, REFUND 回退原节点, CANCEL_CASE 异常结案, CANCEL_UPLOAD 取消上传"
    dealWithError(params) {
      console.log('异常处理：', params);
      api.process(params).then(res => {
        const { responseCode } = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          if (params.exceptionCategory === 'RESTART') {
            // 重新发起 
            this.$notify({
              title: '差错操作重新发起成功',
              type: 'success',
              position: 'top-right',
              duration: 1000
            });
          } else if (params.exceptionCategory === 'REFUND') {
            // 回退原节点
            this.$notify({
              title: '进件/借款退回原节点成功',
              type: 'success',
              position: 'top-right',
              duration: 1000
            });
          } else if (params.exceptionCategory === 'CANCEL_CASE') {
            // 异常结案
            this.$notify({
              title: '进件/借款取消成功',
              type: 'success',
              position: 'top-right',
              duration: 1000
            });
          } else if (params.exceptionCategory === 'CANCEL_UPLOAD') {
            // 取消上传
            this.$notify({
              title: '取消上传成功',
              type: 'success',
              position: 'top-right',
              duration: 1000
            });
          }
          this.selectList = []
          this.onSearch();
        }
      }).catch(() => {})
    }
  }
}
</script>
